import time

from flask import Flask, render_template, request, json, jsonify
import redis

r = redis.Redis(host='localhost', db=0)
app = Flask(__name__)

ONE_WEEK_IN_SECONDS = 86400
VOTE_SCORE = 432


@app.route("/")
def hello_world():
    return render_template('index.html')


@app.get('/articles')
def get_articles():
    timestamp = int(time.time())
    return jsonify({'code': 200, 'data': timestamp})


# TODO wait transaction implement
@app.post('/vote')
async def article_vote():
    article = request.args.get('article_id', '')
    user = request.args.get('user', '')
    cutoff = time.time() - ONE_WEEK_IN_SECONDS
    if r.zscore('time:', article) < cutoff:
        return

    article_id = article.partition(':')[-1]
    if await r.sadd('voted:' + article_id, user):
        await r.zincrby('score:', VOTE_SCORE, article)
        await r.hincrby(article, 'votes', 1)

    return jsonify({'code': 200})


@app.post('/post')
async def article_post():
    user = request.args.get('user', '')
    title = request.args.get('title', '')
    link = request.args.get('link', '')

    article_id = r.incr('article:')
    voted = f'voted:{article_id}'
    await r.sadd(voted, user)
    await r.expire(voted, ONE_WEEK_IN_SECONDS)
    article = f'article:{article_id}'
    now = time.time()
    await r.hset(article, mapping={
        'title': title,
        'link': link,
        'poster': user,
        'votes': 1,
        'time': str(now),
    })

    await r.zadd('score:', mapping={
        article: voted
    })
    await r.zadd('article:', {
        article: now
    })

    return article_id


@app.post('/games')
def add_game():
    name = request.args.get('name', '')
    score = request.args.get('score', 100)
    r.zadd('games', score, name)

    return jsonify({'code': 200, 'data': None})


@app.get('/billboard')
def billboard():
    return render_template('hello.html')
